package cn.itcast.zt.java8.model.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * create by zhangtian105 on 2021/9/15
 */
public class PersonInterceptor implements MethodInterceptor {

    private Transaction transaction ;
    private Object target ;

    public PersonInterceptor(Object target, Transaction transaction) {
        this.target = target ;
        this.transaction = transaction ;
    }

    /**
     * 代理类是目标类的子类
     * @return
     */
    public Object createProxy() {
        Enhancer enhancer = new Enhancer() ;
        enhancer.setCallback(this); // this 指向拦截器
        enhancer.setSuperclass(PersonDaoImpl.class);

        return enhancer.create() ; // 产生代理对象
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        String methodName = method.getName() ;

        if ("updatePerson".equals(methodName) || "savePerson".equals(methodName) || "deletePerson".equals(methodName)) {
            this.transaction.beginTransaction();
            method.invoke(this.target, objects) ; // 目标对象的目标方法
            this.transaction.commit();
        }else {
            method.invoke(this.target, objects) ; // 目标对象的目标方法
        }

        return null;
    }
}
